package com.ewei.web.common.utils;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
 * 路径工具类
 * @author David
 *
 */
public class PathUtils {
	private static final Logger logger = LogManager.getLogger(PathUtils.class);
	private PathUtils(){
	}
	/**
	 * 格式化成标准路径
	 * @param path
	 * @return
	 */
	public static String format(String path){
		Pattern pattern = Pattern.compile("\\\\+|/+");
		Matcher matcher = pattern.matcher(path);
		String formatPath = matcher.replaceAll("/");
		if(formatPath.endsWith("/")){
			formatPath = formatPath.substring(0, path.length()-1);
		}
		return formatPath;
	}
	/**
	 * 相对路径转化为绝对路径
	 * @param path
	 * @param basePath
	 * @return
	 */
	public static String formatToAbsolute(String path,String basePath){
		try {
			URI uri = new URI(basePath);
			URI abs = uri.resolve(path);
			return  abs.toString();
		} catch (URISyntaxException e) {
			logger.info(e);
			throw new IllegalArgumentException("the path is illegal");
		}
	}
}
